import time

class parseURL(object):
    def __init__(self, url, tab):
        self.url = url
        self.tab = tab
        self._get()
    def _get(self):
        self.tab.get(self.url)

        self.tab.scroll.to_location(0, 800)
        # page.scroll.to_bottom()
        self.tab.wait.load_start()  # 等待页面开始加载
        self.tab.wait.doc_loaded()  # 等待页面加载完成

        # 视频暂停
        self.tab.actions.move_to((400, 400))
        self.tab.actions.click()

        self.tab.wait.title_change('评论')  # 等待title变化出现目标文本
        self.tab.stop_loading()  # 主动停止加载
        # return self.tab.get(self.url)
    
    def _close(self):
        self.tab.close()

    def _defineParsefields(self):
        """
        寻找页面的信息，以及页面标签中的类信息
        """
        Parsefields = {
            'title': '.video-info-title-inner',
            'play_count': '.view-text',
            'comment_count': '.dm-text',
            'author': '.up-detail-top', # 作者信息,取第0个
            'description': '.desc-info-text',
            'lables': '.tag-panel',
            # 点赞，投币，收藏，分享
            'like': '.video-like-info video-toolbar-item-text',
            'coin': '.video-coin-info video-toolbar-item-text',
            'collect': '.video-fav-info video-toolbar-item-text',
            'share': '.video-share-info-text'
        }
        return Parsefields
    def getElementsByClass(self, ChromiumElement, class_):
        """
        ChromiumElement: 使用get访问的页面, 都可以使用eles
        _class: 形式,". bili-video-card__wrap"
        """
        return ChromiumElement.eles(class_)
    
    def getElementByClass(self, ChromiumElement, class_):
        """
        ChromiumElement: 使用get访问的页面, 都可以使用eles
        _class: 形式,". bili-video-card__wrap"
        """
        return ChromiumElement.ele(class_)
    
    def getElementsById(self, ChromiumElement, id_):
        """
        ChromiumElement: 使用get访问的页面, 都可以使用eles
        _class: 形式,"#one"
        """
        return ChromiumElement.eles(id_)
    
    def getElementById(self, ChromiumElement, id_):
        """
        ChromiumElement: 使用get访问的页面, 都可以使用eles
        _class: 形式,"#one"
        """
        return ChromiumElement.ele(id_)
    
    def getElementByXpath(self, ChromiumElement, xpath_):
        """
        ChromiumElement: 使用get访问的页面, 都可以使用ele
        _class: 形式,"xpath:.//div"
        """
        return ChromiumElement.ele(f"xpath:.{xpath_}")
    
    def getInfo(self, ChromiumElementsList):
        if ChromiumElementsList == []: return ''
        return ChromiumElementsList[0].text
    
    def convertDict(self, info):
        # 处理数字型信息
        for key, value in info.items():
            if key in ['play_count', 'comment_count', 'like', 'coin', 'collect', 'share']:
                try:
                    info[key] = int(value)
                except:
                    info[key] = 0
            elif key == 'author':
                info[key] = value.split(' ')[0]
            
            else:
                info[key] = value
        
        return info

    def parseComment(self, Parsefields):

        if Parsefields:
            Parsefields['comments-author'] = ''
            Parsefields['comments-content'] = ''
            Parsefields['comments-time'] = ''
        # 第1层：commentapp
        bili_comments1 = self.tab.ele('xpath://*[@id="commentapp"]/bili-comments')
        if not bili_comments1: 
            print("未找到元素")
            return Parsefields
        shadow1 = bili_comments1.shadow_root

        # 第2层：bili-comments
        bili_comments2 = shadow1.child('#contents').child('#feed')
        bili_comments2 = bili_comments2.ele('t:bili-comment-thread-renderer')
        if not bili_comments2: 
            print("未找到标签 -> t:bili-comment-thread-renderer")
            return Parsefields
        shadow2 = bili_comments2.shadow_root

        # 第3层：comment
        bili_comments3 = shadow2.child('#comment')
        shadow3 = bili_comments3.shadow_root

        # 第4层：
        bili_comments4 = shadow3.child('#body').child('#main')
        
        # 第五层, 访问header/content/footer,
        # 访问header
        header = bili_comments4.child('#header')
        header = header.ele('t:bili-comment-user-info')
        header = header.shadow_root
        headerInfo = header.child('#info')

        # content
        content = bili_comments4.child('#content')
        content = content.ele('t:bili-rich-text')
        content = content.shadow_root
        contentInfo = content.child('#contents')

        # 访问footer
        footer = bili_comments4.child('#footer')
        footer = footer.ele('t:bili-comment-action-buttons-renderer')
        footerInfo = footer.shadow_root
        # print("点赞人数", footer.child('#like'))

        # Parsefields['comments'] = {
        #     'author': headerInfo.child('#user-name').text,
        #     'content': contentInfo.child('t:span').text,
        #     'time': footerInfo.child('#pubdate').text,
        #     'like': footerInfo.child('#like').text if footerInfo.child('#like').text else 0,
        #     'dislike': footerInfo.child('#dislike').text if footerInfo.child('#dislike').text else 0,
        # }
        Parsefields['comments-author'] = headerInfo.child('#user-name').text if headerInfo.child('#user-name').text else ''
        Parsefields['comments-content'] = "/".join(contentInfo.texts()) if contentInfo.texts() else ''
        Parsefields['comments-time'] = footerInfo.child('#pubdate').text if footerInfo.child('#pubdate').text else ''
        # 获取评论列表
        return Parsefields
    
    def parseData(self):
        Parsefields = self._defineParsefields()


        for key, value in Parsefields.items():
            elements = self.getElementsByClass(self.tab, value)
            Parsefields[key] = self.getInfo(elements)

        # 转换成json
        Parsefields = self.convertDict(Parsefields)
        # 增加第一条评论
        Parsefields = self.parseComment(Parsefields)

        return Parsefields
        # self._close()